<template>
  <div class="config-page">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <input
        v-model="searchKeyword"
        class="form-control"
        placeholder="搜索聚集名称/聚集描述"
        @keyup.enter="handleSearch"
      />
      <input
        v-model="searchIdNumber"
        class="form-control"
        placeholder="搜索身份证号码/护照号码"
        @keyup.enter="handleSearch"
      />
      <el-select
        v-model="searchFenceStatus"
        placeholder="请选择监控状态"
        style="width: 160px;"
        clearable
      >
        <el-option :key="1" :label="'正在监控'" :value="1">正在监控</el-option>
        <el-option :key="2" :label="'已经失效'" :value="2">已经失效</el-option>
      </el-select>
      <button @click="handleSearch" class="btn btn-secondary">
        <i class="fa fa-search mr-1"></i>搜索
      </button>
      <button @click="clearSearch" class="btn btn-outline-secondary">
        <i class="fa fa-refresh mr-1"></i>清空
      </button>
      <button @click="openCreateConfigDialog" class="btn btn-primary">
        <i class="fa fa-plus mr-1"></i> 新建聚集
      </button>
    </div>

    <!-- 配置表格 -->
    <div class="table-container">
      <el-table
        :data="configPage.list"
        border
        stripe
        :row-class-name="rowClassNameHandler"
        style="width: 100%"
      >
        <el-table-column label="聚集名称" prop="name" width="150"/>
        <el-table-column label="开始时间" prop="startTime" width="180"/>
        <el-table-column label="结束时间" prop="endTime" width="180"/>
        <el-table-column label="聚集距离(米)" prop="distance" width="110"/>
        <el-table-column label="时间间隔(分钟)" prop="interval" width="120"/>
        <el-table-column
          label="创建时间"
          prop="createTime"
          width="170"
          :formatter="(row) => formatDateTime(row.createTime)"
        />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <button @click.stop="handleEditConfig(scope.row)" class="btn btn-sm btn-primary">
              <i class="fa fa-edit mr-1"></i>编辑
            </button>
            <button @click.stop="handleShowPersonList(scope.row)" class="btn btn-sm btn-primary">
              <i class="fa fa-users mr-1"></i>涉及人员
            </button>
            <button @click.stop="handleDeleteConfig(scope.row.id)" class="btn btn-sm btn-danger">
              <i class="fa fa-trash mr-1"></i>删除
            </button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParam.pageNo"
        :page-sizes="[10, 20, 50]"
        :page-size="pageParam.pageSize"
        :total="configPage.total"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <el-drawer
      v-model="showPersonListDrawer"
      title="添加涉及人员"
      direction="rtl"
      size="55%"
      :resizable="true"
    >
      <!-- 标题下方的阴影分隔线 -->
<!--      <div class="header-divider"></div>-->

      <!-- 人员列表组件 -->
      <PersonFenceWarnDrawer
        ref="personListRef"
        :warn-config-id="currentRow?.id"
        @cancel="showPersonListDrawer = false"
      />
    </el-drawer>

    <!-- 新增/编辑配置弹窗（可移动） -->
    <el-dialog
      v-model="showConfigDialog"
      :title="isEditConfig ? '编辑聚集配置' : '新建聚集配置'"
      width="500px"
      :close-on-click-modal="false"
      ref="configDialogRef"
      class="draggable-dialog"
    >
      <div class="form-group">
        <label>聚集名称 <span class="required">*</span>:</label>
        <input
          v-model="configForm.name"
          class="form-control"
          required
          placeholder="请输入聚集名称"
        />
      </div>

      <div class="form-group">
        <label>开始时间 <span class="required">*</span>:</label>
        <el-date-picker
          v-model="configForm.startTime"
          type="datetime"
          class="w-full"
          placeholder="选择开始时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          required
        />
      </div>

      <div class="form-group">
        <label>结束时间 <span class="required">*</span>:</label>
        <el-date-picker
          v-model="configForm.endTime"
          type="datetime"
          class="w-full"
          placeholder="选择结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          required
        />
      </div>

      <div class="form-group">
        <label>聚集距离(米):</label>
        <input
          v-model="configForm.distance"
          type="number"
          min="0"
          step="0.1"
          class="form-control"
          placeholder="输入多少距离算聚集（米）"
        />
      </div>

      <div class="form-group">
        <label>时间间隔:</label>
        <input
          value="120"
          v-model="configForm.interval"
          class="form-control"
          type="number"
          placeholder="输入两个点的时间间隔（例如：30表示30分钟，120表示2小时）"
        />
      </div>

      <div class="form-group">
        <label>配置描述:</label>
        <textarea
          v-model="configForm.description"
          class="form-control"
          rows="3"
          placeholder="可选描述信息"></textarea>
      </div>

      <template #footer>
        <button @click="showConfigDialog = false" class="btn btn-secondary mr-5">
          <i class="fa fa-times mr-1"></i>取消
        </button>
        <button @click="submitConfigForm" class="btn btn-primary">
          <i class="fa fa-check mr-1"></i>提交
        </button>
      </template>
    </el-dialog>

    <!-- 状态提示 -->
    <div v-if="message" class="status-message">{{ message }}</div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, reactive, toRefs, watch} from 'vue';
import {MapConfigApi} from '@/api/member/map/mapConfigApi';
import PersonFenceWarnDrawer from "@/views/warnSetting/components/PersonFenceWarnDrawer.vue";
import {nextTick} from 'vue';
import {ElMessage} from 'element-plus';

defineOptions({name: 'GatherIndex'})

// 类型定义 - 与数据库表结构对应
interface MapConfig {
  id: string;
  name: string;
  description: string;
  startTime: string;
  endTime: string;
  distance?: number;
  interval?: string;
  warnType?: number;
}

// 响应式状态
const state = reactive({
  configPage: {list: [] as MapConfig[], total: 0},
  pageParam: {pageNo: 1, pageSize: 10},
  searchKeyword: '',
  searchIdNumber: '',
  searchFenceStatus: undefined as number | undefined,
  selectedConfigId: '',
  currentConfig: null as MapConfig | null,
  showConfigDialog: false,
  isEditConfig: false,
  configForm: {
    id: '',
    name: '',
    description: '',
    startTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
    endTime: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' '),
    distance: 100, // 默认100米
    interval: '30m', // 默认30分钟
    warnType: 2, // 聚集预警
  },
  message: '',
  loading: false,
});

const {
  configPage, pageParam, searchKeyword, searchIdNumber, searchFenceStatus, selectedConfigId, currentConfig,
  showConfigDialog, isEditConfig, configForm, message, loading
} = toRefs(state);

// 弹窗引用（用于拖拽）
const configDialogRef = ref<HTMLElement | null>(null);

// 抽屉显示状态
const showPersonListDrawer = ref(false);
const personListRef = ref<InstanceType<typeof PersonFenceWarnDrawer>>();

// 当前选中的行数据
const currentRow = ref<MapConfig | null>(null);

// 打开涉及人员抽屉
const handleShowPersonList = (row: MapConfig) => {
  currentRow.value = row;
  showPersonListDrawer.value = true;
  // 触发数据刷新
  nextTick(() => {
    personListRef.value?.fetchPersonList(row.id);
  });
};

// 格式化日期时间（支持数字时间戳和字符串）
const formatDateTime = (cellValue: string | number) => {
  if (!cellValue) return '';

  // 处理数字类型的时间戳
  const timestamp = typeof cellValue === 'string'
    ? parseInt(cellValue, 10)
    : cellValue;

  // 验证时间戳有效性
  if (isNaN(timestamp) || timestamp <= 0) return '';

  const date = new Date(timestamp);

  // 检查日期是否有效
  if (isNaN(date.getTime())) return '';

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 消息提示
const setMessage = (text: string, type: 'success' | 'error' | 'info' = 'info', duration = 3000) => {
  ElMessage({
    message: text,
    type,
    duration
  });
};

// 获取配置列表
const getConfigPage = async () => {
  try {
    loading.value = true;
    const params = {
      pageNo: pageParam.value.pageNo,
      pageSize: pageParam.value.pageSize,
      keyword: searchKeyword.value,
      idNumber: searchIdNumber.value,
      fenceStatus: searchFenceStatus.value,
      warnType: 2 // 聚集预警类型
    };

    const res = await MapConfigApi.getMapConfigPage(params);
    if (res && res.list) {
      configPage.value.list = res.list;
      configPage.value.total = res.total || 0;
    } else {
      configPage.value.list = [];
      configPage.value.total = 0;
    }
  } catch (error) {
    console.error('获取配置列表失败:', error);
    setMessage('获取配置列表失败', 'error');
  } finally {
    loading.value = false;
  }
};

// 搜索配置
const handleSearch = () => {
  pageParam.value.pageNo = 1;
  getConfigPage();
};

// 清空搜索条件
const clearSearch = () => {
  // 重置所有搜索绑定的变量
  searchKeyword.value = '';
  searchIdNumber.value = '';
  searchFenceStatus.value = undefined;
  // 可选：清空后自动执行一次搜索，显示所有数据
  handleSearch();
};


// 表格行样式
const rowClassNameHandler = ({row}: { row: MapConfig }) => {
  return row.id === selectedConfigId.value ? 'selected-config' : '';
};

// 打开新增配置弹窗
const openCreateConfigDialog = () => {
  isEditConfig.value = false;
  // 设置默认值，包括当前时间和30天后的结束时间
  const now = new Date();
  const defaultEndTime = new Date(now);
  defaultEndTime.setDate(now.getDate() + 30);
  configForm.value = {
    id: '',
    name: '',
    description: '',
    startTime: now.toISOString().slice(0, 19).replace('T', ' '),
    endTime: defaultEndTime.toISOString().slice(0, 19).replace('T', ' '),
    distance: 100,
    interval: '30',
    warnType: 2,
  };
  showConfigDialog.value = true;
};

// 编辑配置
const handleEditConfig = (row: MapConfig) => {
  isEditConfig.value = true;
  // 复制行数据到表单，并为可选字段提供默认值
  configForm.value = {
    ...row,
    // 确保日期格式正确
    startTime: row.startTime ? new Date(row.startTime).toISOString().slice(0, 19).replace('T', ' ') : '',
    endTime: row.endTime ? new Date(row.endTime).toISOString().slice(0, 19).replace('T', ' ') : '',
    // 为可选字段提供默认值，避免undefined
    distance: row.distance ?? 100,  // 使用空值合并运算符提供默认值
    interval: row.interval ?? '30',
    warnType: row.warnType ?? 2
  };
  showConfigDialog.value = true;
};

// 删除配置
const handleDeleteConfig = async (id: string) => {
  if (!confirm('确定要删除该配置吗？关联的数据也会被删除。')) {
    return;
  }

  try {
    loading.value = true;
    await MapConfigApi.deleteMapConfig(id);
    setMessage('配置已成功删除', 'success');
    await getConfigPage();

    // 如果删除的是当前选中的配置，清除选中状态
    if (id === selectedConfigId.value) {
      selectedConfigId.value = '';
      currentConfig.value = null;
    }
  } catch (error) {
    console.error('删除配置失败:', error);
    setMessage('删除配置失败', 'error');
  } finally {
    loading.value = false;
  }
};

// 提交配置表单
const submitConfigForm = async () => {
  // 表单验证
  if (!configForm.value.name.trim()) {
    setMessage('请填写聚集名称', 'error');
    return;
  }

  if (!configForm.value.startTime) {
    setMessage('请选择开始时间', 'error');
    return;
  }

  if (!configForm.value.endTime) {
    setMessage('请选择结束时间', 'error');
    return;
  }

  // 验证时间逻辑
  const startTime = new Date(configForm.value.startTime);
  const endTime = new Date(configForm.value.endTime);
  const now = new Date();

  if (startTime >= endTime) {
    setMessage('开始时间不能晚于结束时间', 'error');
    return;
  }

  if (endTime < now) {
    setMessage('结束时间不能早于当前时间', 'error');
    return;
  }

  try {
    loading.value = true;

    if (isEditConfig.value) {
      // 更新配置
      await MapConfigApi.updateGatherConfig(configForm.value);
      setMessage('配置已成功更新', 'success');
    } else {
      // 创建新配置
      await MapConfigApi.createGatherConfig(configForm.value);
      setMessage('配置已成功创建', 'success');
    }

    // 关闭弹窗并刷新列表
    showConfigDialog.value = false;
    await getConfigPage();
  } catch (error) {
    console.error(isEditConfig.value ? '更新配置失败:' : '创建配置失败:', error);
    setMessage(isEditConfig.value ? '更新配置失败' : '创建配置失败', 'error');
  } finally {
    loading.value = false;
  }
};

// 分页大小变更
const handlePageSizeChange = (size: number) => {
  pageParam.value.pageSize = size;
  pageParam.value.pageNo = 1;
  getConfigPage();
};

// 当前页变更
const handleCurrentChange = (page: number) => {
  pageParam.value.pageNo = page;
  getConfigPage();
};

// 生命周期 - 挂载时
onMounted(() => {
  getConfigPage();
});

// 监听配置弹窗关闭
watch(showConfigDialog, (newVal) => {
  if (!newVal) {
    // 弹窗关闭时的清理工作
  }
});
</script>

<style scoped>
.config-page {
  padding: 20px;
  //max-width: 1400px;
  margin: 0 auto;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  max-width: 820px;
}

.search-bar .form-control {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.table-container {
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

/* 可移动弹窗样式 */
.draggable-dialog .el-dialog__header {
  cursor: move;
  user-select: none; /* 防止拖拽时选中标题文字 */
}

.draggable-dialog .el-dialog__body {
  cursor: default;
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}

.draggable-dialog {
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  margin: 0 !important;
  transition: none !important;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #333;
}

.required {
  color: #f44336;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
  transition: border-color 0.2s;
}

.form-control:focus {
  border-color: #42b983;
  outline: none;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  transition: background-color 0.2s;
}

.btn-primary {
  background-color: #42b983;
  color: white;
}

.btn-primary:hover {
  background-color: #359e75;
}

.btn-secondary {
  background-color: #e5e7eb;
  color: #374151;
}

.btn-secondary:hover {
  background-color: #d1d5db;
}

.btn-danger {
  background-color: #f44336;
  color: white;
}

.btn-danger:hover {
  background-color: #d32f2f;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
  margin-right: 5px;
}

.mr-1 {
  margin-right: 5px;
}

.status-message {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 10px 15px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 4px;
  z-index: 1000;
}

.selected-config {
  background-color: #e6f7ee;
}

.header-divider {
  height: 4px;
  background: linear-gradient(90deg, #42b983, #117a8b);
  border-radius: 1px;
}

/* 加载状态覆盖层 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}
/* 可选：调整按钮间距 */
.search-bar .btn {
  margin-left: 8px;
}

/* 可选：清空按钮悬停效果 */
.btn-outline-secondary:hover {
  background-color: #f5f5f5;
}

.btn-primary {
  background-color: #42b983;
  color: white;
}

.btn-warning {
  background-color: #f39c12; /* 橙色作为警告色主色调 */
  color: white; /* 白色文字确保可读性 */
}

/* 可选：添加悬停效果增强交互体验 */
.btn-warning:hover {
  background-color: #e67e22; /* 稍深的橙色作为悬停状态 */
}

:deep(.el-drawer__header) {
  margin-bottom: 0 !important;
}
</style>
